/*
 * @Author: 哈兰德
 * @Description: 根store
 */
import tool from '@/util/tool.js'
import { SELF_RULE_FILTER_COMPONENTS } from '@/util/biz/dic'
export const state = () => ({
  isInMobile: false,
})

export const mutations = {
  setMobileORManagement (state, value) {
    state.isInMobile=value
  }
}


export const actions = {

  async nuxtServerInit ({ commit,dispatch },context) {
    const  { query, req,$info  } =context
    $info(`[page url]${req.url}`)
    commit('server/setUserAgent', req.headers['user-agent'])
    if (req.url.includes('management')){
      query.shiro_sid && commit('server/setShiroSid', query.shiro_sid)
    }
    if (query.activityCode && req.url.includes('mobile')){
      commit('server/setQuery', query)
      await dispatch('loadJson',{ ...context,dispatch })
    }
  },
  async loadJson ({ commit, dispatch },context){
    const { query,$axios,res  } =context
    let jsonBody = ''
    if (query.type && query.type==='preview'){
      // 从数据库调取json
      let response =await $axios.post('/activity/getActivityJsonInfo',{ activityCode:query.activityCode } )
      jsonBody = response.data
    } else {
      let url= tool.getPageJsonUrl(query.activityCode)
      // 从CDN拿一次
      console.log('=======>>>>我看看是从哪里拿到的', url)
      console.log('=======>>>>axios.baseUrl', $axios)
      // baseURL
      // jsonBody = await $axios.get(url).catch((e) => {
      //   console.log('从CDN拿JSON失败：'+e.meassage)
      // })
      // if (!jsonBody){
      // 从CDN没有拿到，再从数据库拿一次
      const jsonRep=await $axios.post('/activity/getActivityJsonInfoPublished',{ 
        activityCode:query.activityCode })
      console.log('jsonRep', jsonRep)
      if (jsonRep.flag==='S'){
        jsonBody=JSON.parse(jsonRep.data) 
      }
      // }
    }
    if (!jsonBody){
      // 仍然没取到json（活动创建后从来没发布过等其他原因）
      jsonBody={
        componentList:[]
      }
      res.end('<h1>The activity is not exsit , please make sure you have published !</h1> ')
    }
    let mouse=jsonBody.componentList.find(a => a.code==='BeatMouseModule')
    let queryData={ 
      activityCode:query.activityCode,
      gameNo:(mouse?mouse.gameNo:'') 
    }
    let activity =await $axios.post('/activity/queryActivityIsStarted',queryData )
    if (activity && activity.flag==='S'){
      jsonBody.activityStatus=activity.data.activityStatus
      if (activity.data.activityStatus!==0){
        // 活动如果未上线，将组件list置空，避免组件渲染
        jsonBody.componentList=[]
      }
      if (mouse){ mouse.gameStatus=activity.data.gameStatus } 
    }
    commit('main/setPageContent',jsonBody)
    await dispatch('checkRule',context)
  },
  async checkRule ({ commit, dispatch },context) {
    const { store } = context
    let userNo = store.state.server.userNo
    if (!userNo) {
      commit('main/showAllComponents')
      return
    }
    await dispatch('getNeedRuleFilter',context)
  },
  async getNeedRuleFilter ({ commit, dispatch },context) {
    const { store } =context
    let ruleQueryList = []
    // 将ruleButton转化成普通组件，以便统一处理人群
    let ruleButton={ 
      _id:'rule-' + store.state.server.activityCode,
      code:'ruleButton',
      type:'hidden',
      ...store.state.main.pageContent.ruleButton
    }
    commit('main/addComponent',ruleButton)

    let list=store.state.main.pageContent.componentList

    // 只能用for循环，await在foreach中不起效
    for (let i=0;i<list.length;i++){
      let element=list[i]
      let id = await dispatch('dealComponentRule',{ item:element })
      if (id) {
        // 组件设置了人群规则(此标记通知组件内部业务接口，需要人群过滤)
        commit('main/setQueryRuleTag',{ id:element._id,tag:true })
        if (!SELF_RULE_FILTER_COMPONENTS.includes(element.code)){
          // 简单组件
          ruleQueryList.push(id)
        } else {
          // 自处理规则的业务组件
          commit('main/setComponentVisible',{ id:id,visible:true })
        }
      }
    }
    if (ruleQueryList.length > 0) {
      await dispatch('queryRules',{ ruleQueryList, ...context })
    }
  },
  async dealComponentRule ({ commit },{ item }) {
    if (!item.childRuleTag && (!item.rule || !item.rule.tag)){
      commit('main/setComponentVisible',{ id:item._id,visible:true })
      return
    } 
    if (item.rule && item.rule.onlineTime && item.rule.offlineTime) {
      let now = new Date().getTime()
      let start = new Date(item.rule.onlineTime).getTime()
      let end = new Date(item.rule.offlineTime).getTime()
      if (now >= start && now <= end) {
        // 在有效时间内，依然要调用接口，服务端验证时间有效性
        return item._id
      } else {
        commit('main/setComponentVisible',{ id:item._id,visible:false } )
        return
      }
    } else {
      return item._id
    }
  },
  async queryRules ({ commit, dispatch },request) {
    const { ruleQueryList,query,$axios,store } = request
    let requestData={
      activityCode: query.activityCode,
      moduleCodes: ruleQueryList,
      userNo: store.state.server.userNo,
      versionDomain:store.state.server.versionRule
    }
    let res =await $axios.post('/v2/rule/rulesFilter', requestData).catch(async () => {
      commit('main/hideComponents',ruleQueryList)
    })
    if (res.flag === 'S') {
      await dispatch('handleQueryResults',{ list:res.data })
    } else {
      commit('main/hideComponents',ruleQueryList)
    }
  },
  async handleQueryResults ({ commit },{ list }) {
    list.forEach((item) => {
      commit('main/setComponentVisible',{ id:item.moduleCode,visible:item.hit })
      commit('main/setComponentRuleContens',{ id:item.moduleCode,arr:item.results })
    })
  }
}
